package bTree.LeetCode;

public class 搜索旋转排序数组 {
    public int search(int[] nums, int target) {
        int length = nums.length;
        if (length == 1) {
            return nums[0] == target ? 0 : -1;
        }
        //搜索分界线
        int interval = searchInterval(nums);
        if (nums[interval] == target) {
            return interval;
        }
        if (target >= nums[0] && target < nums[interval]) {
            return twoSearch(0, interval - 1, target, nums);
        } else {
            return twoSearch(interval + 1, length - 1, target, nums);
        }
    }

    private int twoSearch(int i, int i1, int target, int[] nums) {
        int left = i, right = i1;
        int mid = (left + right) / 2;
        while (left <= right) {
            mid = (left + right) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] == target) {
                return mid;
            }
        }
        return -1;
    }

    private int searchInterval(int[] nums) {
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] < nums[i - 1]) {
                return i - 1;
            }
        }
        return nums.length-1;
    }
}